<template>
  <div class="eco">
    <div class="search">
      <div class="search-ttile">区间</div>
      <el-select v-model="searchData.searchDate" placeholder="请选择" @change="changeSelect">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <div class="search-ttile">时间</div>
      <el-date-picker
          v-model="searchData.searchDate1"
          style="margin-left: 20px"
          type="daterange"
          range-separator="~"
          :default-time="['00:00:00', '23:59:59']"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          v-if="datePickerType =='daterange'"
      />
      <el-date-picker
          v-model="searchData.searchDate1"
          style="margin-left: 20px"
          type="year"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          v-if="datePickerType =='year'"
      />
      <el-date-picker
          v-model="searchData.searchDate1"
          style="margin-left: 20px"
          type="monthrange"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          v-if="datePickerType =='month'"
      />
      <div class="search-button">
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button type="info" @click="handleExport">导出</el-button>
      </div>
    </div>
    <div class="table" v-if="tableData && tableData.length>0">
      <el-table
          class="bueatyScroll"
          :data="tableData"
          style="width: 100%;margin-bottom: 20px;"
          row-key="value"
          border
          default-expand-all
          max-height="800"
          id="exportTab"
          ref="eltable"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column
            label="名称"
            prop="label"
            width="400"
            fixed
        >
          <template slot-scope="scope">
            <span>{{ scope.row.index1 }} {{ scope.row.label }}</span>
            <!--            <span>{{ scope.row.label }}</span>-->
          </template>
        </el-table-column>
        <el-table-column
            :label="i.name"
            :width="i.width"
            v-for="(i,index) in columnData"
            :key="index"
        >
          <template slot-scope="scope" v-if="scope.row.datalistMax.value">
            <span v-if="index%2==0" style="color: #4b67af">
              {{ scope.row.datalistMin.value[index / 2].v || 0 }}
            </span>

            <span v-else-if="index%2!=0" style="color: red">
              {{ scope.row.datalistMax.value[(index - 1) / 2].v || 0 }}
            </span>
            <span v-else>0</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import {exportExcel} from "@/utils/excelConfig";
import {getNeworganizations, getSpandata} from '@/api/eco'
import {login} from "@/api";
import {setCookieToken} from "@/utils/auth";
import {mapActions, mapMutations} from "vuex";
import {formatTime1, indexData, toTree} from '@/utils/index'
import FileSaver from "file-saver";
import XLSX from "xlsx";
import {endDate, endMonthDate, endYearDate, startDate, startYearDate} from "@/utils/time";

export default {
  name: "ecoWatch",
  async mounted() {
    this.SET_TOKEN('')
    let username = 'admin@advantech.com'
    let password = window.btoa('8IrXJ3XPr4dMgnQQ')
    const res = await login({username, password})
    setCookieToken(res.accessToken)
    this.SET_TOKEN(res.accessToken)


    this.searchData.searchDate1 = [startDate(), endDate()];


    await this.getList()


    setInterval(async () => {
      let username = 'admin@advantech.com'
      let password = window.btoa('8IrXJ3XPr4dMgnQQ')
      const res = await login({username, password})
      setCookieToken(res.accessToken)
      await this.SET_TOKEN(res.accessToken)
      console.log('res=>', res)
    }, 1000 * 60 * 30)
  },
  data() {
    return {
      options: [{
        value: '1y',
        label: '年'
      }, {
        value: '1M',
        label: '月'
      }, {
        value: '1d',
        label: '日'
      }
        // {
        //   value: 'min',
        //   label: '分'
        // }
      ],
      searchData: {
        searchDate: '1d',
        searchDate1: []
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      columnData: [
        {prop: "label", width: 300, name: "日期"}
      ],
      tableData: [],
      menuList: {},
      tableColumn: [],
      datePickerType: "daterange"

    };
  },
  methods: {
    ...mapActions(['setSize']),
    ...mapMutations(['SET_TOKEN']),
    search() {
      this.getList()
    },
    changeSelect(e) {
      if (e == '1y') {
        this.datePickerType = 'year'
        this.searchData.searchDate1 = [];
      }
      if (e == '1M') {
        this.datePickerType = 'month'
        this.searchData.searchDate1 = [];
      }
      if (e == '1d') {
        this.searchData.searchDate1 = [startDate(), endDate()];
        this.datePickerType = 'daterange'
      }
      console.log('this.datae=>', this.datePickerType)
    },
    async getList() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      const res1 = await getNeworganizations() // 菜单数据
      this.menuList = res1[2]


      let arrList = this.treeToArray(this.menuList.children)//数组拍平
      console.log('arrList=>', arrList)
      const paramsV1 = this.paramsData(arrList, 'max') // 重组查询数据
      const paramsV2 = this.paramsData(arrList, 'min') // 重组查询数据

      const res2Max = await getSpandata(paramsV1)
      const res2Min = await getSpandata(paramsV2)

      let columnList = []
      let length = Number(res2Max[0].count) * 2
      let timeArrIndex = 0
      for (let i = 0; i < length; i++) {
        let obj = {
          name: '',
          prop: 'value',
          width: 150,
        }
        let timeArr = res2Max[0].value.map((v, index) => v.ts)
        if (i % 2 == 0) {
          console.log('111=>', 111)
          obj.name = formatTime1(timeArr[timeArrIndex], this.datePickerType) + '最小值'
        } else {
          obj.name = formatTime1(timeArr[timeArrIndex], this.datePickerType) + '最大值'
          console.log('222=>', 222)
          timeArrIndex = timeArrIndex + 1
        }
        console.log('obj=>', obj)
        obj.index = i
        columnList.push(obj)
      }
      console.log('columnList=>', columnList)
      // console.log('co=>', columnList)
      this.columnData = columnList
      arrList.map(v1 => {
        res2Max.map(v2 => {
          if (v1.value == v2.nodeId) {
            v1.datalistMax = v2
          }
        })
        res2Min.map(v2 => {
          if (v1.value == v2.nodeId) {
            v1.datalistMin = v2
          }
        })
      })
      // this.tableData = toTree(arrList, '3976')
      var tabArr = toTree(arrList, '3976')

      tabArr = indexData(tabArr)
      // console.log('tabArr=>', tabArr)
      this.tableData = tabArr


      console.log('tableData=>', this.tableData)
      let timer = setTimeout(() => {
        loading.close();
        clearTimeout(timer)
      }, 1000)


    },
    download() {
      exportExcel('能管需量分析表格', this.exc_data);
    },
    listToTree(cityList) {
      let array = []
      cityList.forEach(item => { // 遍历对象数组
        item.children = cityList.filter(info => info.parentId === item.value) // 找到每个对象的子节点
        if (item.parentId === 0) {
          array.push(item) // 将一层节点放入新数组中
        }
      })
      return array //循环结束，返回结果
    },

    //数组拍平
    treeToArray(tree) {
      return tree.reduce((res, item) => {
        const {children, ...i} = item
        return res.concat(i, children && children.length ? this.treeToArray(children) : [])
      }, [])
    },

    paramsData(arr = [], type = 'max') {
      let obj = {}

      const body = {
        "sensors": [],
        "notAllowDefault": false,
        "retTsType": "unixTs",
        "interval": this.searchData.searchDate,
        "startTs": "",
        "endTs": "",
      }

      console.log('body=>', this.searchData)
      if (this.searchData.searchDate == 'min') {
        delete body.interval
      }
      if (this.datePickerType == 'year') {
        body.startTs = startYearDate(this.searchData.searchDate1)
        body.endTs = endYearDate(this.searchData.searchDate1)
      }
      if (this.datePickerType == 'daterange') {
        body.startTs = this.searchData.searchDate1[0].toISOString()
        body.endTs = this.searchData.searchDate1[1].toISOString()
      }
      if (this.datePickerType == 'month') {
        let time = JSON.parse(JSON.stringify(this.searchData))
        console.log('time=>', time)
        body.startTs = time.searchDate1[0]
        body.endTs = endMonthDate(new Date(time.searchDate1[1]))
      }
      arr.map(v => {
        if (type == 'max') {
          obj = {
            "dataType": "max",
            "default": 0,
            "nodeId": Number(v.value),
            "sensorName": "15 Minutes 电_AP",
            "sensorType": "ANOM"
          }
        } else {
          obj = {
            "dataType": "min",
            "default": 0,
            "nodeId": Number(v.value),
            "sensorName": "15 Minutes 电_AP",
            "sensorType": "ANOM"
          }
        }
        body.sensors.push(obj)
      })
      return body
    },
    //导出
    handleExport() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      try {
        const $e = this.$refs['eltable'].$el
        let $table = $e.querySelector('.el-table__fixed')
        if (!$table) {
          $table = $e
        }
        const wb = XLSX.utils.table_to_book($table, {raw: false})
        let wbout1 = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'})
        FileSaver.saveAs(
            new Blob([wbout1], {type: 'application/octet-stream'}),
            `能管.xlsx`,
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e)
      }
      loading.close()
      // return wbout1;
    },
    changeqj(v) {
      console.log('v=>', v)
    },
    getDate(time) {
      if (time) {
        let val = new Date(time);
        let Y = val.getFullYear();
        let M = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1);
        let D = val.getDate() < 10 ? '0' + val.getDate() : val.getDate();
        return time;
      }
      return ''
    }
  },
}
;
</script>
<style lang="scss" scoped>
#app {
  background-color: #eceeef;
}

.eco {
  padding: 30px;
}

.search {
  display: flex;
  background-color: #fff;

  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 10px;

  .search-ttile {
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    margin: 0 10px;
  }

  .search-button {
    margin-left: 20px;
  }
}

.table {
  margin-top: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

::v-deep {
  .el-table {
    border-radius: 5px;
  }

  .el-table__body-wrapper::-webkit-scrollbar-track-piece {
    background-color: #f8f8f8;
  }

  .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px;
  }

  .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #dddddd;
    border-radius: 100px;
  }

  .el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
    background-color: #bbb;
  }
}

/*
*改变浏览器默认的滚动条样式
*/

</style>
